<?php
class ciqueueClient
{
    private $m_host;
    private $m_port;
    private $m_sock;

    public function __construct($strHost, $intPort)
    {
        $this->m_host = $strHost;
        $this->m_port = $intPort;
        $this->m_sock = NULL;
        $this->_connect();
    }

    private function _connect()
    {
        $this->m_sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); 
        socket_set_option($this->m_sock, SOL_SOCKET, SO_SNDTIMEO, array( "sec"=>0, "usec"=>100000 ) );
        return socket_connect($this->m_sock, $this->m_host, $this->m_port); 
    }

    private function _check_conntect()
    {
        $ret = @socket_recv($this->m_sock, $rstr, 1, MSG_DONTWAIT);
        if (0 === $ret)
        {
//            echo "remote close\n";
            socket_close($this->m_sock);
            return $this->_connect();
        }
        else if ($ret === false)
        {
//            echo "timeout\n";
            return true;
        }
        return true;
    }

    /* 返回 FALSE 表示失败，成功时返回写入的字节数 */
    public function commit($intLogID, $strQueueName, $strOperation, $arrOperationBody)
    {
        if ($this->_check_conntect())
        {
            $sendArray = array();
            $sendArray['__QUEUE_NAME__']     = $strQueueName;
            $sendArray['__OPERATION__']      = $strOperation;
            $sendArray['__OPERATION_BODY__'] = $arrOperationBody;

            $jsonstr = json_encode($sendArray);
            $FORMAT_XHEAD = "Ilogid/a16hiname/Iversion/Ireserved/Idetail_len";
            $binaryData = pack("Ia16III", $intLogID, "ccphp", 0, 0, strlen($jsonstr));
            $binaryData .= $jsonstr;
//            var_dump(unpack($FORMAT_XHEAD, $binaryData));
            socket_set_option($this->m_sock, SOL_SOCKET, SO_RCVTIMEO, array( "sec"=>1, "usec"=>0 ) );
            socket_set_option($this->m_sock, SOL_SOCKET, SO_SNDTIMEO, array( "sec"=>1, "usec"=>0 ) );
            socket_write($this->m_sock, $binaryData);
            $rstr = socket_read($this->m_sock, 32);
            if (32 != strlen($rstr))
            {
                return FALSE;
            }
            $retArray = unpack($FORMAT_XHEAD, $rstr);
//            var_dump($retArray);
            return $retArray["reserved"] == 0; 
        }
        else
        {
            return FALSE;
        }
    }
}

?>
